//
// Created by hlx on 2021/12/31.
//

#include <stdio.h>
#include <time.h>

#include "native.h"
#include "vm.h"
#include "memory.h"

Value gcNative(int argCount, Value *args) {
    if (argCount > 0) {
        runtimeError("param is too many");
    }
    collectGarbage();
    return NULL_VAL;
}

Value clockNative(int argCount, Value *args) {
    if (argCount > 0) {
        runtimeError("param is too many");
    }
    return NUMBER_VAL((double) clock() * 1000 / CLOCKS_PER_SEC);
}

Value typeofNative(int argCount, Value *args) {
    if (argCount != 1) {
        runtimeError("params number is error");
        return NULL_VAL;
    }
    char *types[] = {"string", "boolean", "null", "number", "object"};
    if (IS_STRING(args[0])) {
        return OBJ_VAL(copyString(types[0], strlen(types[0])));
    } else if (IS_BOOL(args[0])) {
        return OBJ_VAL(copyString(types[1], strlen(types[1])));
    } else if (IS_NULL(args[0])) {
        return OBJ_VAL(copyString(types[2], strlen(types[2])));
    } else if (IS_NUMBER(args[0])) {
        return OBJ_VAL(copyString(types[3], strlen(types[3])));
    }
    return OBJ_VAL(copyString(types[4], strlen(types[4])));
}

Value requireNative(int argCount, Value *args) {
    if (argCount != 1 || !IS_STRING(args[0])) {
        runtimeError("param must be a string");
        return NULL_VAL;
    }

    runFile(AS_CSTRING(args[0]));

    return NULL_VAL;
}

Value printNative(int argCount, Value *args) {
    if (argCount == 0) {
        printf("\n");
        return NULL_VAL;
    }
    if (argCount != 1) {
        runtimeError("params number is error");
        return NULL_VAL;
    }
    printValue(args[0]);
    printf("\n");
    return NULL_VAL;
}